#include "TestTaskService.hpp"
#include "stdio.h"
/* RTOS */
#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"
/* 标准库 */
#include "string.h"
/* Driver */
#include "SerialPort.hpp"
#include "FatFs.hpp"
#include "usart.h"
#include "usart1_printf.h"
#include "SPILcd.hpp"
#include "lcd_fonts.h"
/* LVGL */
#include "lvgl.h"                // 它为整个LVGL提供了更完整的头文件引用
#include "lv_port_disp.h"        // LVGL的显示支持
#include "lv_port_indev.h"       // LVGL的触屏支持

static TaskHandle_t test_task;

void LCD_Test_All(SPILcd* lcd) {
    printf("LCD_Test_All START\r\n");

    lcd->setBackColor(LCD_BLACK);
    lcd->setColor(LCD_WHITE);
    lcd->clear();  // 清空屏幕

    // 1. 点和线测试
    lcd->setColor(LIGHT_RED);
    lcd->drawPoint(10, 10);
    lcd->drawLineH(20, 30, 100);
    lcd->drawLineV(30, 50, 100);
    lcd->drawLine(10, 10, 100, 100);

    // 2. 矩形测试
    lcd->setColor(LIGHT_GREEN);
    lcd->drawRect(50, 50, 60, 40);
    lcd->fillRect(120, 50, 60, 40);

    // 3. 圆和椭圆测试
    lcd->setColor(LIGHT_BLUE);
    lcd->drawCircle(60, 150, 20);
    lcd->fillCircle(120, 150, 20);
    lcd->drawEllipse(180, 150, 30, 15);

    // 4. 显示字符
    lcd->setColor(LIGHT_YELLOW);
    lcd->setAsciiFont(&ASCII_Font24);
    lcd->displayChar(10, 200, 'A');
    lcd->displayString(30, 200, (char *)"Hello");

    // 5. 数字显示测试
    lcd->setColor(LIGHT_MAGENTA);
    lcd->displayNumber(10, 220, 123, 5);
    lcd->displayDecimals(100, 220, 3.1416, 7, 3);

    uint16_t testWidth = 80, testHeight = 80;
    static uint16_t flushColor[80 * 80];  // 1200 个像素，确保足够
    for (int i = 0; i < testWidth * testHeight; ++i) {
        flushColor[i] = 0xF800;  // 红色 RGB565
    }
    lcd->fillFlush(180, 180, 180 + testWidth - 1, 180 + testHeight - 1, flushColor);
    // 等待显示 3 秒
    vTaskDelay(1000);
    lcd->clear();

    printf("LCD_Test_All END\r\n");
}

void MonitorTaskStack() {
    UBaseType_t high_water_mark = uxTaskGetStackHighWaterMark(nullptr); // 获取当前任务的最小剩余栈
    printf("Task Stack High Water Mark: %lu words (%lu bytes)\r\n", 
           high_water_mark, high_water_mark * sizeof(StackType_t));
}

static void TestTaskService_task(void *param){
    SerialPort * serial_port = SerialPort::getInstance(1);
    FatFs * fs = FatFs::getInstance(1);
    SPILcd * spi_lcd = SPILcd::getInstance(0);

    /* LCD 测试 */
    spi_lcd->init();
    printf("LCD Init OK\r\n");
    lv_init();                             // LVGL 初始化
    lv_port_disp_init();                   // 注册LVGL的显示任务
    // lv_port_indev_init();                  // 注册LVGL的触屏检测任务

    // 按钮
    lv_obj_t *myBtn = lv_btn_create(lv_scr_act());                               // 创建按钮; 父对象：当前活动屏幕
    lv_obj_set_pos(myBtn, 10, 10);                                               // 设置坐标
    lv_obj_set_size(myBtn, 120, 50);                                             // 设置大小

    // 按钮上的文本
    lv_obj_t *label_btn = lv_label_create(myBtn);                                // 创建文本标签，父对象：上面的btn按钮
    lv_obj_align(label_btn, LV_ALIGN_CENTER, 0, 0);                              // 对齐于：父对象
    lv_label_set_text(label_btn, "Test");                                        // 设置标签的文本
 
    // 独立的标签
    lv_obj_t *myLabel = lv_label_create(lv_scr_act());                           // 创建文本标签; 父对象：当前活动屏幕
    lv_label_set_text(myLabel, "Hello world!");                                  // 设置标签的文本
    lv_obj_align(myLabel, LV_ALIGN_CENTER, 0, 0);                                // 对齐于：父对象
    lv_obj_align_to(myBtn, myLabel, LV_ALIGN_OUT_TOP_MID, 0, -20);               // 对齐于：某对象


    while(1){
        // LCD_Test_Clear(spi_lcd);
        // LCD_Test_Text(spi_lcd);
        lv_timer_handler();  // 刷新 LVGL 内部任务
        vTaskDelay(pdMS_TO_TICKS(5)); // 或 HAL_Delay(5);
        // LCD_Test_All(spi_lcd);

    }

    unsigned char serial_rx_buffer[256];      // 串口接收缓冲区
    int serial_tx_counter = 0;                // 串口发送计数
    
    int file_write_count = 0;                 // 写文件次数
    char file_write_buffer[64];              // 写文件缓冲区
    char file_read_buffer[64] = {0};        // 读文件缓冲区
    

    // 删除旧文件
    FRESULT del_res = f_unlink("1:/test.txt");
    if (del_res == FR_OK || del_res == FR_NO_FILE) {
        printf("File deleted or did not exist.\n");
    } else {
        printf("File delete failed: %d\n", del_res);
    }

    while( true ){

        // 每次写一行数据（追加方式打开）
        if (fs->open("1:/test.txt", FA_WRITE | FA_OPEN_APPEND)) {
            sprintf(file_write_buffer, "%d\r\n", file_write_count++);
            fs->write(file_write_buffer, strlen(file_write_buffer));
            fs->close();  // 一定要关闭！
        }

        // 读取整个文件验证内容（可选）
        if (fs->open("1:/test.txt", FA_READ)) {
            int len = fs->read(file_read_buffer, sizeof(file_read_buffer) - 1);
            file_read_buffer[len] = '\0';
            printf("Read from SD:\n%s\n", file_read_buffer);
            fs->close();  // 一定要关闭！
        }

        /* 测试1串口发送 */
        printf("serial_tx_counter:%d\r\n",serial_tx_counter);
        serial_tx_counter = (serial_tx_counter + 1) % 10000;
        
        /* 测试1串口接收 */
        int length = serial_port->receive(serial_rx_buffer);
        if( length > 0){
            for( int i = 0; i < length; i++){
                printf("%x\r\n",serial_rx_buffer[i]);
            }
        }

        vTaskDelay(1000);
    }
}

bool TestTaskService::run(){
    xTaskCreate(TestTaskService_task,"TestTaskService_task",2048,nullptr,1,&test_task);
    return true;
}
